<template>
  <div>
    <div>
      <el-button type="danger" size="small" @click="deleteData">{{
        $t("删除")
      }}</el-button>
      <el-button type="danger" size="small" @click="deleteAllData">{{
        $t("清空报表")
      }}</el-button>
    </div>
    <el-table size="mini" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column type="selection" align="center" min-width="55"></el-table-column>
      <el-table-column prop="fileName" :label="$t('报表名称')" min-width="120">
        <template slot-scope="scope">
          <tooltip :html="scope.row.fileName" :content="scope.row.fileName" class="wid190" :refName="scope.row.fileName">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="type" :label="$t('报表周期')" min-width="100">
        <template slot-scope="scope">
          {{ $t(timeTypeList[scope.row.type]) }}
        </template>
      </el-table-column>
      <el-table-column prop="time" :label="$t('报表生成时间')" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.time }}
        </template>
      </el-table-column>
      <el-table-column prop="name" :label="$t('报表任务名称')" min-width="120">
        <template slot-scope="scope">
          <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column align="center" width="160" fixed="right" :label="$t('操作')">
        <template slot-scope="scope">
          <el-button type="success" plain size="mini" @click="dialogVisibleOpen(scope.row)">{{ $t("下载数据") }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 图表内容生成下载 -->
    <el-dialog width="70%" custom-class="my-dialog" top="100px" :close-on-click-modal="false" v-drag v-if="exportEchartShow" :visible.sync="exportEchartShow">
      <template slot="title">
        <span>{{ $t("文件类型：") }}</span>
        <el-radio-group v-model="record.type">
          <el-radio label="html">HTML</el-radio>
          <el-radio label="pdf">PDF</el-radio>
          <el-radio label="word">WORD</el-radio>
        </el-radio-group>
        <el-button size="small" style="margin-left: 30px" :loading="loading" @click="handleDownload">{{ $t("下载") }}</el-button>
      </template>
      <div class="my-content" ref="myContent" style="back">
        <el-row v-for="(item, index) in info.template_stats" :key="index">
          <el-col :span="spanWidth">
            <div v-if="index === 0">
              <el-card class="my-card title" :body-style="bodyStyle">
                <div>{{ $t("防火墙统计报告") }}</div>
              </el-card>
              <el-card class="my-card">
                <div class="card-info-title">{{ $t("报表信息") }}</div>
                <div class="my-card-info">
                  <div class="card-info-item">
                    <span>{{ $t("报告名称：") }}</span>
                    <span>{{ $t(info.report_name) }}</span>
                  </div>
                  <div class="card-info-item">
                    <span>{{ $t("报告任务名称：") }}</span>
                    <span>{{ $t(info.report_crond_name) }}</span>
                  </div>
                  <div class="card-info-item">
                    <span>{{ $t("报表生成时间：") }}</span>
                    <span>{{info.report_create_time && moment(info.report_create_time * 1000 ).format('YYYY-MM-DD HH:mm:ss') || null}}</span>
                  </div>
                  <div class="card-info-item">
                    <span>{{ $t("报表周期类型：") }}</span>
                    <span>{{ $t(info.report_period) }}</span>
                  </div>
                  <div class="card-info-item">
                    <span>{{ $t("报表开始日期：") }}</span>
                    <span>{{info.report_statistical_from_time && moment(info.report_statistical_from_time * 1000).format('YYYY-MM-DD HH:mm:ss') || null}}</span>
                  </div>
                  <div class="card-info-item">
                    <span>{{ $t("报表结束日期：") }}</span>
                    <span>{{info.report_statistical_to_time && moment(info.report_statistical_to_time * 1000).format('YYYY-MM-DD HH:mm:ss') || null}}</span>
                  </div>
                </div>
              </el-card>
            </div>
            <div class="my-descriptions">
              <div class="card-info-title card-info-title-line">
                <span>{{ $t("图表展示") }}</span>
              </div>
              <div class="descriptions-item" style="margin-top: 16px">
                <span>{{ $t("模板名称：") }}</span>
                <span>{{ $t(item.template_name) }}</span>
              </div>
              <div class="descriptions-item" style="margin-top: 16px">
                <span>{{ $t(item.stats_title) }}</span>
              </div>
            </div>
            <div v-show="item.stats && Object.keys(item.stats).length" :ref="`bar${index}`" :class="`bar${index}`" style="width: 100%; height: 500px"></div>
          </el-col>
          <el-col :span="spanWidth" v-show="item.stats && Object.keys(item.stats).length">
            <div :ref="`pie${index}`" :class="`pie${index}`" style="width: 100%; height: 500px; margin-top: 32px"></div>
          </el-col>
          <el-col :span="24" v-show="!(item.stats && Object.keys(item.stats).length)">
            <el-empty :image-size="200"></el-empty>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from 'moment'
import {
  getReportDownloadArray,
  delReportDownload,
  clearReportDownload,
  getReportData,
} from "@/api/system/logReport/diyReport";
import {
  exportToHtml,
  exportToWord,
  exportToPdf,
} from "@/utils/exportToFiles.js";
import { eye_show, eye_hide } from "./eye.js";
export default {
  name: "DownloadReport",
  data() {
    return {
      moment,
      info: {},
      loading: false,
      dialogVisible: false,
      exportEchartShow: false,
      record: {
        name: "",
        type: "html",
      },
      bodyStyle: {
        background: "rgb(26, 179, 148)",
        "text-align": "center",
        color: "#ffffff",
        "font-size": "30px",
        "font-weight": "700",
      },
      spanWidth: 24,
      tableData: [],
      toImg: [],
      timeTypeList: {
        single: this.$t("历史报表"),
        loop: this.$t("周期性报表"),
      },
      lang: this.$i18n.locale
    };
  },
  mounted() {
    this.listData();
  },
  methods: {
    // 下载
    handleDownload() {
      this.loading = true;
      if (this.record.type === "html") {
        exportToHtml(
          this.record.name,
          this.$refs.myContent.outerHTML,
          this.info,
          () => {
            this.loading = false;
          }
        );
      }
      if (this.record.type === "pdf") {
        exportToPdf(this.record.name, this.$refs.myContent, () => {
          this.loading = false;
        });
      }
      if (this.record.type === "word") {
        exportToWord(this.record.name, this.$refs.myContent, this.toImg, () => {
          this.loading = false;
        });
      }
    },
    // 柱状图
    bar(info) {
      const list = info.template_stats
      for (let i = 0; i < list.length; i++) {
        const { stats } = list[i];
        const keys = Object.keys(stats).map((item) =>
          item === "" ? (this.lang === 'zh' ? '其他':'other') : item
        );
        const values = Object.values(stats);
        const myChart = this.$echarts.init(this.$refs["bar" + i][0], null, {
          devicePixelRatio: 2,
        });
        const option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true,
          },
          xAxis: [
            {
              type: "value",
              axisTick: {
                alignWithLabel: true,
              },
            },
          ],
          yAxis: [
            {
              type: "category",
              axisTick: { show: true }, // y轴刻度线
              data: keys,
              axisLabel: { interval: 0 },
              margin: 5,
            },
          ],
          series: [
            {
              name: "Value",
              type: "bar",
              // barWidth: 20,
              data: values,
              // itemStyle: {
              //   normal: {
              //     label: {
              //       show: true,
              //       position: "right",
              //       formatter: "{c}", //这是关键，在需要的地方加上就行了
              //     },
              //   },
              // },
            },
          ],
        };
        myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      }
    },
    // 饼图
    pie(info) {
      const list = info.template_stats
      for (let i = 0; i < list.length; i++) {
        const data = [];
        for (const key in list[i].stats) {
          data.push({
            name: key === "" ? (this.lang === 'zh' ? '其他':'other')  : key,
            value: list[i].stats[key],
          });
        }
        const myChart = this.$echarts.init(this.$refs["pie" + i][0], null, {
          devicePixelRatio: 2,
        });
        const option = {
          toolbox: {
            show: true,
            feature: {
              myTool: {
                show: true,
                title: this.$t("隐藏图例"),
                icon: list[i].legendShow ? eye_show : eye_hide,
                onclick: () => {
                  list[i].legendShow = !list[i].legendShow;
                  myChart.setOption({
                    legend: {
                      show: list[i].legendShow,
                      orient: "vertical",
                      left: "left",
                    },
                    toolbox: {
                      show: true,
                      feature: {
                        myTool: {
                          show: true,
                          title: list[i].legendShow ? this.$t("隐藏图例") : this.$t("显示图例"),
                          icon: list[i].legendShow ? eye_show : eye_hide,
                        },
                      },
                    },
                    series: [
                      {
                        center: [list[i].legendShow ? "60%" : "50%", "50%"], // 设置饼图居中
                      },
                    ],
                  });
                },
              },
            },
          },
          tooltip: {
            trigger: "item",
          },
          legend: {
            show: true,
            orient: "vertical",
            left: "left",
          },
          series: [
            {
              // name: list[i].stats_title,
              type: "pie",
              radius: "50%",
              center: ["60%", "50%"], // 设置饼图居中
              data,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: "rgba(0, 0, 0, 0.5)",
                },
              },
            },
          ],
        };
        myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      }
    },
    // 多选按钮
    handleSelectionChange(data) {
      var nameStr = "";
      for (var item of data) {
        if (nameStr === "") {
          nameStr = item.fileName;
        } else {
          nameStr = nameStr + "@#@" + item.fileName;
        }
      }
      this.nameStr = nameStr;
    },
    listData() {
      getReportDownloadArray().then((res) => {
      if (res.status === 0) {
        this.tableData = res.info;
      }
      });
    },
    deleteData() {
      if (this.nameStr) {
        this.$confirm(
          this.$t("您是否要删除所有选中的数据？"),
          this.$t("提示"),
          {
            closeOnClickModal: false,
            confirmButtonText: this.$t("确定"),
            cancelButtonText: this.$t("取消"),
            confirmButtonClass: "confirmButton",
            cancelButtonClass: "confirmCancelButton",
            type: "warning",
          }
        ).then(() => {
          delReportDownload({ name: this.nameStr }).then((res) => {
            if (res.status === 0) {
              this.$message({
                message: this.$t("删除成功"),
                type: "success",
              });
              this.nameStr = "";
              this.listData();
            }
          });
        });
      } else {
        this.$messages.error(this.$t("请至少选择一条数据进行删除"));
      }
    },
    deleteAllData() {
      this.$confirm(this.$t("您是否要清空所有数据？"), this.$t("提示"), {
        closeOnClickModal: false,
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        confirmButtonClass: "confirmButton",
        cancelButtonClass: "confirmCancelButton",
        type: "warning",
      }).then(() => {
        clearReportDownload().then((res) => {
          if (res.status === 0) {
            this.$message({
              message: this.$t("清空成功"),
              type: "success",
            });
            this.listData();
          }
        });
      });
    },
    downloadReportData() {
      const params = {
        name: this.record.name,
      };
      getReportData(params).then((res) => {
      const { status, info } = res;
      if (status === 0) {
        this.info = info;
        this.info.lang = this.lang;
        this.info.template_stats = this.info.template_stats.map((item) => ({
          ...item,
          legendShow: true,
        }));
        for (let i = 0; i < this.info.template_stats.length; i++) {
          this.toImg.push(`.bar${i}`);
          this.toImg.push(`.pie${i}`);
        }
        this.exportEchartShow = true;
        this.$nextTick(() => {
          this.bar(this.info);
          this.pie(this.info);
        });
      }
      });
    },
    close() {
      this.exportEchartShow = false;
      this.record.type = "html";
      this.record.name = "";
    },
    dialogVisibleOpen(data) {
      this.exportEchartShow = true;
      this.record.name = data.fileName;
      this.loading = false;
      this.downloadReportData();
    },
  },
};
</script>
<style lang="less" scoped>
.my-content {
  min-height: 700px;
  max-height: 700px;
  overflow-x: hidden;
  overflow-y: auto;
  .card-info-title {
    font-size: 16px;
    font-weight: 700;
    color: #333;
  }
  .my-card {
    &:not(:first-child) {
      margin-top: 16px;
    }
    .my-card-info {
      display: flex;
      flex-flow: row wrap;
      .card-info-item {
        width: 33.33%;
        padding-top: 16px;
      }
    }
  }
  .my-descriptions {
    margin-top: 20px;
    display: flex;
    flex-flow: row wrap;
    .descriptions-item {
      width: 100%;
    }
    .card-info-title-line {
      position: relative;
      &:before {
        content: "";
        position: absolute;
        width: 4px;
        height: 15px;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        background-color: rgb(26, 179, 148);
      }
      span {
        margin-left: 20px;
      }
    }
  }
}
</style>
